<template>
   <div class="app-container">
      <el-form :model="queryParams" ref="queryRef" :inline="true" v-show="showSearch">
         <el-form-item label="数据集" prop="ds_id">
               <el-select v-model="queryParams.ds_id" placeholder="数据集" clearable style="width: 200px">
                  <el-option
                     v-for="dict in dsList"
                     :key="dict.id"
                     :label="dict.name"
                     :value="dict.id"
                  />
               </el-select>
         </el-form-item>
         <el-form-item label="摄像机" prop="camera_id">
               <el-select v-model="queryParams.camera_id" placeholder="摄像机" clearable style="width: 200px">
                  <el-option
                     v-for="dict in cameraList"
                     :key="dict.id"
                     :label="dict.name"
                     :value="dict.id"
                  />
               </el-select>
         </el-form-item>
         <el-form-item label="状态" prop="status">
            <el-select v-model="queryParams.status" placeholder="状态" clearable style="width: 200px">
               <el-option
                  v-for="dict in sys_status"
                  :key="dict.value"
                  :label="dict.label"
                  :value="dict.value"
               />
            </el-select>
         </el-form-item>
         <el-form-item label="分组" prop="category">
            <el-select v-model="queryParams.category" placeholder="分组" clearable style="width: 200px">
               <el-option
                  v-for="dict in sys_type"
                  :key="dict.value"
                  :label="dict.label"
                  :value="dict.value"
               />
            </el-select>
         </el-form-item>
         <el-form-item>
            <el-button type="primary" icon="Search" @click="handleQuery">搜索</el-button>
            <el-button icon="Refresh" @click="resetQuery">重置</el-button>
         </el-form-item>
      </el-form>

      <el-table v-loading="loading" :data="imageList">
         <el-table-column label="图片名称" align="center" prop="name">
            <template #default="scope">
               <image-preview :src="'/images/view/'+scope.row.id" :width="80" :height="80"/>
            </template>
         </el-table-column>
         <el-table-column label="分组" align="center" prop="category" width="100">
            <template #default="scope">
               <dict-tag :options="sys_type" :value="scope.row.category" />
            </template>
         </el-table-column>
         <!--el-table-column label="标注人" align="center" prop="user_name" width="100" /-->
         <el-table-column label="状态" align="center" prop="status" width="100">
            <template #default="scope">
               <dict-tag :options="sys_status" :value="scope.row.status" />
            </template>
         </el-table-column>
         <el-table-column label="采集时间" align="center" prop="create_time" />
         <el-table-column label="标记时间" align="center" prop="update_time" />
         <el-table-column label="操作" align="center" class-name="small-padding fixed-width">
            <template #default="scope">
               <el-button link type="primary" icon="Edit" @click="handleUpdate(scope.row)">标注</el-button>
            </template>
         </el-table-column>
      </el-table>

      <pagination
         v-show="total > 0"
         :total="total"
         v-model:page="queryParams.page"
         v-model:limit="queryParams.limit"
         @pagination="getList"
      />

      <!-- 添加或修改公告对话框 -->
      <el-dialog :title="title" v-model="open" width="800px" append-to-body>
            <div id="mark-container"></div>
            <hr />
         <el-form ref="formRef" :model="form" :rules="rules" label-width="120px">  
            <el-form-item label="标签" prop="text" v-if="currLabel">
               <el-select v-model="form.text" placeholder="请选择标签" @change="changeLabel" style="width: 400px;">
                  <el-option
                     v-for="dict in labelOptions"
                     :key="dict"
                     :label="dict"
                     :value="dict"
                  />
               </el-select>
            </el-form-item>
         </el-form>
         <template #footer>
            <div class="dialog-footer">
               <el-button type="danger" @click="clearLabels">清 空</el-button>
               <el-button @click="cancel">取 消</el-button>
               <el-button type="primary" @click="saveImage">保 存</el-button>
            </div>
         </template>
      </el-dialog>
   </div>
</template>

<script setup name="ImageMark">
import SimpleImageLabel from 'simple-image-label'
import { listImage, getImage, delImage, addImage, updateImage } from "@/api/image";
import { listDataset } from "@/api/dataset";
import { listCamera } from "@/api/camera";
import { nextTick } from 'vue';
import { ref } from 'vue';

const { proxy } = getCurrentInstance();
const sys_status = [{value:'0', label:'未标记'}, {value:'1', label:'已标记'}, {value:'2', label:'已审核'}];
const sys_type = [{value:'train', label:'训练集'}, {value:'test', label:'测试集'}, {value:'val', label:'验证集'}];
const imageList = ref([]);
const dsList = ref([]);
const cameraList = ref([]);

const open = ref(false);
const loading = ref(false);
const showSearch = ref(true);
const total = ref(0);
const title = ref("");
const baseURL = import.meta.env.VITE_APP_BASE_API
const simpleImageLabel = ref(null);
const currLabel = ref(null);
const currImage = ref(null);
const dataset = ref(null);
const labelOptions = ref(null);

const data = reactive({
  form: {text: null},
  queryParams: {
    page: 1,
    limit: 10,
    name: undefined,
    ds_id: undefined,
    camera_id: undefined,
    category: undefined,
    status: '0'
  },
  rules: {
    name: [{ required: true, message: "采集任务名称不能为空", trigger: "blur" }],
    status: [{ required: true, message: "状态不能为空", trigger: "change" }],
    camera_id: [{ required: true, message: "摄像机不能为空", trigger: "change" }],
    ds_id: [{ required: true, message: "数据集不能为空", trigger: "change" }],
  },
});

const { queryParams, form, rules } = toRefs(data);

/** 查询采集任务列表 */
function getList() {
  loading.value = true;
  listImage(queryParams.value).then(response => {
    imageList.value = response.rows;
    total.value = response.total;
    loading.value = false;
  });
}
/** 取消按钮 */
function cancel() {
  open.value = false;
  reset();
}
/** 表单重置 */
function reset() {
  form.value = {
    name: undefined,
    camera_id: undefined,
    ds_id: undefined,
    status: "0"
  };
  proxy.resetForm("formRef");
}
/** 搜索按钮操作 */
function handleQuery() {
   if(!queryParams.value.ds_id) {
      proxy.$modal.msgError("请选择数据集");
      imageList.value = [];
      return;
   }
  queryParams.value.pageNum = 1;

  getList();

  for(let item of dsList.value) {
    if(queryParams.value.ds_id == item.id) {
      dataset.value = item;
      labelOptions.value = item.classes.split('\n');
      console.log(labelOptions.value);
      break;
    }
  }
}
/** 重置按钮操作 */
function resetQuery() {
  proxy.resetForm("queryRef");
  handleQuery();
}

/**修改按钮操作 */
function handleUpdate(row) {
   open.value = true;
   currImage.value = row;
   form.value.text = null;
   nextTick(() => {
      simpleImageLabel.value = new SimpleImageLabel({
         el: 'mark-container',
         imageUrl: baseURL + '/images/view/' + row.id,
         labels: row.annotations ? row.annotations : [],
         contextmenu: (e) => {
            console.log(e);
         },
         labelClick: (label) => {
            currLabel.value = label;
            console.log(label);
            form.value.text = label.name;
         },
         error: (e) => {
            console.log(e);
         }
      });
   });
}

function changeLabel() {
  if (form.value.text == null) {
    proxy.$modal.msgError("请标注文本");
    return;
  }
  currLabel.value.name = form.value.text;
  currLabel.value.color = '#FF0000';
  simpleImageLabel.value.setLabelByUuid(currLabel.value.uuid, currLabel.value);
}

function saveImage() {
   currImage.value.status = '1';
   currImage.value.annotations = simpleImageLabel.value.getLabels()
   updateImage(currImage.value).then(response => {
      proxy.$modal.msgSuccess("标注成功");
      open.value = false;
      getList();
   });
}

/** 清空标注 */
function clearLabels() {
   simpleImageLabel.value.removeAllLabels();
   currLabel.value = null;
}

listDataset().then(response => {
   dsList.value = response.rows;
});

listCamera().then(response => {
   cameraList.value = response.rows;
});

</script>
